package com.xunyji.demo00testdemo.web.thymeleaf;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xunyji.demo00testdemo.comm.util.weixin.AuthUtil;
import com.xunyji.demo00testdemo.model.weixin.WeixinAuthUserDO;
import com.xunyji.demo00testdemo.model.weixin.WeixinUserInfo;
import com.xunyji.demo00testdemo.repository.WeixinAuthUserRepository;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author AltEnter
 * @create 2019-01-12 15:22
 * @desc 微信授权控制类
 **/
@RequestMapping(value = "/wxAuth")
@Controller
@Slf4j
public class WxAuthController {

    @Autowired
    private WeixinAuthUserRepository weixinAuthUserRepository;

    @GetMapping(value = "/callback")
    public String getUserInfo(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException {
        String code = request.getParameter("code");
        log.info("getCode - 获取到的code为：" + code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=APPID" +
                "&secret=SECRET" +
                "&code=CODE" +
                "&grant_type=authorization_code";
        url = url.replace("APPID", AuthUtil.APPID)
                .replace("SECRET", AuthUtil.APPSECRET)
                .replace("CODE", code);
        log.info("封装好的获取access_token的url为：" + url);
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        log.info("getCode - 获取access_token的响应数据为: " + jsonObject);
        String openid = (String) jsonObject.get("openid");
        String accessToken = (String) jsonObject.get("access_token");

        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=ACCESS_TOKEN" +
                "&openid=OPENID" +
                "&lang=zh_CN";
        infoUrl = infoUrl.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openid);
        log.info("封装好的获取登陆用户信息的url为：" + infoUrl);
        JSONObject infoJsonObject = AuthUtil.doGetJson(infoUrl);
        log.info("getCode - 获取用户信息的响应数据为: " + infoJsonObject);

//        微信用户信息封装
        String str = com.alibaba.fastjson.JSONObject.toJSONString(infoJsonObject);
        WeixinUserInfo weixinUserInfo = com.alibaba.fastjson.JSONObject.parseObject(str, WeixinUserInfo.class);
        log.info("封装好的微信端userinfo为：" + weixinUserInfo);

//        第一种：使用微信用户信息直接登陆，无需注册和绑定
//        map.addAttribute("userInfo", weixinUserInfo);
//        return "index";

//        第二种：微信用户信息和网站用户信息进行绑定
        String weixinOpenid = weixinUserInfo.getOpenid();
        WeixinAuthUserDO weixinAuthUserDO = weixinAuthUserRepository.findByOpenid(weixinOpenid);
        if (weixinAuthUserDO != null) {
//            已经绑定过的情况
            map.addAttribute("userInfo", weixinAuthUserDO);
            return "index2";
        } else {
//            没有绑定过的情况（假设该用户已经注册过啦）
            map.addAttribute("openid", weixinOpenid);
            map.addAttribute("nickname", weixinUserInfo.getNickname());
            return "login";
        }
    }

    @PostMapping(value = "/bind")
    public String bind(WeixinAuthUserDO weixinAuthUserDO, ModelMap map) {
        log.info("bind - 接收到的参数信息为：" + weixinAuthUserDO);
//        TODO: 对账户信息进行格式校验，如果格式不正确直接返回登录绑定页面
//        TODO: 验证账户是否存在, 如果不存在直接跳转到注册页面（微信用户信息同时返回），在注册逻辑中直接进行绑定
//        TODO: 验证账户密码是否正确，如果部正确直接返回登录绑定页面
        WeixinAuthUserDO save = weixinAuthUserRepository.save(weixinAuthUserDO);
        if (save != null) {
            log.info("bind - 绑定成功");
            map.addAttribute("userInfo", save);
            return "index2";
        } else {
            log.info("bind - 绑定失败");
            return "login";
        }
    }

}

